package com.cn.dream_order_server.service.impl;


import com.cn.dream_order_server.async.OrderCartAsync;
import com.cn.dream_order_server.async.WlcDoCreateOrderUtilAsync;
import com.cn.dream_order_server.client.ActivityServer;
import com.cn.dream_order_server.client.GoodServer;
import com.cn.dream_order_server.mapper.OrderOrderMapper;
import com.cn.dream_order_server.pojo.OrderOrder;
import com.cn.dream_order_server.pojo.OrderOrderdetails;
import com.cn.dream_order_server.pojo.OrderShopping;
import com.cn.dream_order_server.pojo.SuccessKilled;
import com.cn.dream_order_server.service.OrderOrder1Service;
import com.cn.dream_order_server.service.OrderOrderdetailsService;
import com.cn.dream_order_server.util.DoCreatOrderUtil;
import com.cn.dream_order_server.util.JsonUtils;
import com.cn.dream_order_server.util.RandomGenUtil;
import com.cn.dream_order_server.vo.Cartvo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Service
public class OrderOrder1ServiceImpl implements OrderOrder1Service {

    @Autowired
    private WlcDoCreateOrderUtilAsync doCreateOrderUtilAsync;


    @Autowired
    private OrderCartAsync orderCartAsync;

    @Autowired
    private OrderOrderdetailsService orderOrderdetailsService;

    @Autowired
    private OrderOrderMapper orderOrderMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ActivityServer activityServer;

    @Autowired
    private GoodServer goodServer;


    @Override
    @Transactional
    public String wlccreateOrderOrderSummary(String[] shoppingIds,String userId,String siteId,Integer cartTatol) {
        //异步查询购物车信息
        Future<List<OrderShopping>> listFuture = orderCartAsync.wlcGetOrderShoppingListInshoppingId(shoppingIds);
        //创建订单对象
        OrderOrder orderOrder = new OrderOrder();
        //订单为对象赋值
        orderOrder.setOrderId(RandomGenUtil.fourRandomGenOrderId());
        orderOrder.setUserId(userId);
        orderOrder.setSiteId(userId);
        orderOrder.setPaytypeId("2");
        orderOrder.setPlaceTime(new Date());
        orderOrder.setOrderTotal(cartTatol);
        orderOrder.setOrdertypeId("1");

        //定义优惠金额
        Integer discountAmount = 0;
        //定义活动类型变量
        String activityYype = null;
        //定义img存放图片
        String img = null;
        //定义list用于存放orderOrderdetails对象
        List<OrderOrderdetails> orderOrderdetailsList = new ArrayList<OrderOrderdetails>();

        //定义List集合用于接收异步的结果
        List<OrderShopping> list = null;
        try {
            list =  listFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //判断结果是否为空
        if(list!=null&&list.size()>0){
            //遍历集合对象
            for (OrderShopping orderShopping:list ) {

                //调用商品服务传入商品id获取vo对象
                // orderShopping.setGoodCommoditySku(vo对象);

                //判断vo对象是否为空
                //判断vo对象中活动id是否为2限时折扣
                //将活动类型变量赋值为2
                //discountAmount=discountAmount+（vo对象.price-vo对象.优惠后金额）
                //判断vo对象中商品库存是否大于购买数量
                //创建订单详情对象
                OrderOrderdetails orderOrderdetails = new OrderOrderdetails();
                //为订单详情对象赋值
                orderOrderdetails.setOrderdetailsId(UUID.randomUUID().toString());
                orderOrderdetails.setOrderId(orderOrder.getOrderId());
                orderOrderdetails.setCommodityId(orderShopping.getCommodityId());
                orderOrderdetails.setCommodityNum(orderShopping.getShoppingNum());
                orderOrderdetails.setCommodityMoney(Integer.valueOf(orderShopping.getShoppingTotal().toString()));
                //将对象存入list集合中
                orderOrderdetailsList.add(orderOrderdetails);

                //elsevo对象中商品库存是否小于购买数量
                return null;

            }

            //img=list.get(0).getGoodCommoditySku().getImages();
        }

        //订单为对象赋值
        orderOrder.setOrderOther2(img);//img第一件商品的img（vo对象中取值）
        //订单为对象赋值
        orderOrder.setOrderOther4(2);
        orderOrder.setDiscountsMoney(discountAmount);//优惠金额
        orderOrder.setActivitytypeId(activityYype);//活动类型id
        //调用服务生成订单
        int i = orderOrderMapper.insert(orderOrder);
        //判断订单是否生成
        if (i==1){
            //调用详情service批量添加详情
            orderOrderdetailsService.saveOrderOrderdetails(orderOrderdetailsList);
            //将数据存入到redis中
            stringRedisTemplate.opsForValue().set("create-order-"+orderOrder.getOrderId(),JsonUtils.objToString(orderOrder),35,TimeUnit.MINUTES);
            DoCreatOrderUtil myCacheUtil = new DoCreatOrderUtil(doCreateOrderUtilAsync);
            myCacheUtil.set(orderOrder.getOrderId(),orderOrder,60*30);
            return orderOrder.getOrderId();
        }
        return null;
    }

    @Override
    public String wlccreateOrderOrderSummary_MS(String shoppingIds, String userId, String siteId, Integer cartTatol) {

        System.out.println(shoppingIds+","+userId+","+siteId+","+cartTatol);
        //获取
        String ylSeckill = activityServer.getKilled(Long.parseLong(shoppingIds));
        System.out.println(ylSeckill);
        SuccessKilled successKilled = JsonUtils.stringToObj(ylSeckill, SuccessKilled.class);
        //获取商品对象
        String cartVo = goodServer.getCartVo((successKilled.getCommodityId()).toString());
        System.out.println(cartVo);
        Cartvo cartvo = JsonUtils.stringToObj(cartVo, Cartvo.class);

        //定义list用于存放orderOrderdetails对象
        List<OrderOrderdetails> orderOrderdetailsList = new ArrayList<OrderOrderdetails>();

        //创建订单对象
        OrderOrder orderOrder = new OrderOrder();
        //为订单详情对象赋值
        orderOrder.setOrderId(RandomGenUtil.fourRandomGenOrderId());//订单id
        orderOrder.setUserId(userId);//用户id
        orderOrder.setSiteId(siteId);//用户地址表id
        orderOrder.setPaytypeId("2");//支付状态id
        orderOrder.setPlaceTime(new Date());//下单时间
        orderOrder.setOrderTotal(cartTatol);//订单总价
        orderOrder.setOrdertypeId("1");//订单状态（1代付款2待收货3已完成4已取消5已删除）
        orderOrder.setOrderOther4(2);//管理员查看订单状态(1已完成2待付款3待发货4待收货5已取消6删除)
        double activityPrice = successKilled.getActivityPrice()*100;
        long  aLong = cartvo.getSku().getPrice();
        Integer discountAmount = (int)(aLong - (long)activityPrice);
        orderOrder.setDiscountsMoney(discountAmount);//优惠金额
        orderOrder.setActivitytypeId("1");//活动类型id
        orderOrder.setOrderOther2(cartvo.getSku().getImages());
        int i = orderOrderMapper.insertSelective(orderOrder);
        if (i==1){
            //创建订单详情对象
            OrderOrderdetails orderOrderdetails = new OrderOrderdetails();
            //为订单详情对象赋值
            orderOrderdetails.setOrderdetailsId(UUID.randomUUID().toString());
            orderOrderdetails.setOrderId(orderOrder.getOrderId());
            orderOrderdetails.setCommodityId(cartvo.getCommodityId());
            orderOrderdetails.setCommodityNum(1);
            orderOrderdetails.setCommodityMoney(cartTatol);
            orderOrderdetailsList.add(orderOrderdetails);
            orderOrderdetailsService.saveOrderOrderdetails(orderOrderdetailsList);
            return orderOrder.getOrderId();
        }
        return null;
    }
}
